package com.cjw.service.impl.database;

import com.cjw.mapper.database.MinioFileMapper;
import com.cjw.pojo.entity.database.MinioFile;
import com.cjw.service.database.MinioService;
import com.cjw.util.MinioUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @create_time:2021.11.13
 * @author :cjw
 * @decripe: Minio文件服务类
 */
@Service("minioService")
public class MinioServiceImpl implements MinioService {

    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private MinioFileMapper minioFileMapper;

    @Transactional(rollbackFor = Exception.class)
    public String MinIOUpload(MultipartFile file, Integer type) {
        if (file.isEmpty() || file.getSize() == 0) {
            return "文件为空";
        }
        try {
            if (!minioUtil.bucketExists("health")) {
                minioUtil.makeBucket("health");
            }

            String fileName = file.getOriginalFilename();
            String newName;
            if (fileName.indexOf(".") == -1) {
                newName = "image/" + UUID.randomUUID().toString().replaceAll("-", "");
            } else {
                newName = "image/" + UUID.randomUUID().toString().replaceAll("-", "")
                        + fileName.substring(fileName.lastIndexOf("."));
            }

            InputStream inputStream = file.getInputStream();
            minioUtil.putObject("health", newName, inputStream);
            inputStream.close();

            MinioFile minioFile = new MinioFile();
            minioFile.setAddTime(new Date());
            minioFile.setUpdateTime(new Date());
            minioFile.setUrl(minioUtil.getObjectUrl("health", newName));
            minioFile.setSize((double) file.getSize());
            minioFile.setType(type);
            minioFile.setDownNumber(0);
            minioFileMapper.insert(minioFile);

            return minioUtil.getObjectUrl("health", newName);
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
    }

    @Override
    public Long getIdByUrl(String url) {
        MinioFile minioFile = new MinioFile();
        minioFile.setUrl(url);
        return minioFileMapper.selectOne(minioFile).getId();
    }


}

